<template>
  <div class="environment-app">
    <header class="app-header">
      <h1>系统环境变量配置</h1>
      <div class="header-info">
        <span class="version">v{{ env.APP_VERSION }}</span>
        <span class="env-badge" :class="envClass">{{ env.APP_ENV }}</span>
        <span class="timestamp">更新时间: {{ currentTime }}</span>
      </div>
    </header>

    <main class="app-main">
      <!-- 环境信息概览 -->
      <section class="env-overview">
        <h2>环境信息概览</h2>
        <div class="overview-grid">
          <div class="overview-item">
            <strong>应用标题:</strong> {{ env.APP_TITLE }}
          </div>
          <div class="overview-item">
            <strong>应用版本:</strong> {{ env.APP_VERSION }}
          </div>
          <div class="overview-item">
            <strong>当前环境:</strong> {{ env.APP_ENV }}
          </div>
          <div class="overview-item">
            <strong>API 地址:</strong> {{ env.API_BASE_URL }}
          </div>
        </div>
      </section>

      <!-- 配置分类展示 -->
      <div class="config-sections">
        <!-- 应用基础配置 -->
        <ConfigSection 
          title="应用基础配置" 
          :config="appConfig"
          icon="🏠"
        />

        <!-- API 配置 -->
        <ConfigSection 
          title="API 配置" 
          :config="apiConfig"
          icon="🔗"
        />

        <!-- 功能开关 -->
        <ConfigSection 
          title="功能开关" 
          :config="featureConfig"
          icon="⚙️"
        />

        <!-- 第三方服务配置 -->
        <ConfigSection 
          title="第三方服务配置" 
          :config="thirdPartyConfig"
          icon="🔧"
        />

        <!-- 业务配置 -->
        <ConfigSection 
          title="业务配置" 
          :config="businessConfig"
          icon="📊"
        />

        <!-- 开发配置 -->
        <ConfigSection 
          title="开发配置" 
          :config="devConfig"
          icon="🛠️"
        />

        <!-- 缓存配置 -->
        <ConfigSection 
          title="缓存配置" 
          :config="cacheConfig"
          icon="💾"
        />

        <!-- 日志配置 -->
        <ConfigSection 
          title="日志配置" 
          :config="logConfig"
          icon="📝"
        />

        <!-- 测试配置 -->
        <ConfigSection 
          title="测试配置" 
          :config="testConfig"
          icon="🧪"
        />
      </div>

      <!-- 环境验证结果 -->
      <section class="validation-section">
        <h2>环境配置验证</h2>
        <div class="validation-result" :class="{ 'valid': validation.isValid, 'invalid': !validation.isValid }">
          <div class="validation-status">
            <span class="status-icon">{{ validation.isValid ? '✅' : '❌' }}</span>
            <span class="status-text">{{ validation.isValid ? '配置验证通过' : '配置验证失败' }}</span>
          </div>
          <div v-if="!validation.isValid" class="validation-errors">
            <h4>错误信息:</h4>
            <ul>
              <li v-for="error in validation.errors" :key="error">{{ error }}</li>
            </ul>
          </div>
        </div>
      </section>

      <!-- 操作面板 -->
      <section class="action-panel">
        <h2>操作面板</h2>
        <div class="action-buttons">
          <button @click="refreshData" class="action-btn primary">
            🔄 刷新数据
          </button>
          <button @click="exportConfig" class="action-btn secondary">
            📤 导出配置
          </button>
          <button @click="copyToClipboard" class="action-btn secondary">
            📋 复制配置
          </button>
          <button @click="toggleAutoRefresh" class="action-btn" :class="{ 'active': autoRefresh }">
            {{ autoRefresh ? '⏸️ 停止自动刷新' : '▶️ 开始自动刷新' }}
          </button>
        </div>
      </section>
    </main>

    <footer class="app-footer">
      <p>&copy; 2024 {{ env.APP_TITLE }}. 环境变量显示模块</p>
      <p class="footer-info">
        环境: {{ env.APP_ENV }} | 
        版本: {{ env.APP_VERSION }} | 
        最后更新: {{ currentTime }}
      </p>
    </footer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { env, validateEnv, getEnvironmentInfo } from '@/utils/env'
import ConfigSection from './components/ConfigSection.vue'

// 响应式数据
const currentTime = ref('')
const autoRefresh = ref(false)
const refreshInterval = ref<number | null>(null)

// 计算属性
const envClass = computed(() => {
  switch (env.APP_ENV) {
    case 'development': return 'env-dev'
    case 'staging': return 'env-staging'
    case 'production': return 'env-prod'
    default: return 'env-unknown'
  }
})

const validation = computed(() => validateEnv())

// 配置数据分组
const appConfig = computed(() => ({
  '应用标题': env.APP_TITLE,
  '应用版本': env.APP_VERSION,
  '应用描述': env.APP_DESCRIPTION,
  '应用环境': env.APP_ENV
}))

const apiConfig = computed(() => ({
  'API 基础地址': env.API_BASE_URL,
  'API 超时时间': `${env.API_TIMEOUT}ms`,
  'API 版本': env.API_VERSION,
  'API 缓存': env.API_CACHE_ENABLED ? '启用' : '禁用'
}))

const featureConfig = computed(() => ({
  '调试模式': env.ENABLE_DEBUG ? '启用' : '禁用',
  '数据分析': env.ENABLE_ANALYTICS ? '启用' : '禁用',
  '错误监控': env.ENABLE_ERROR_MONITORING ? '启用' : '禁用',
  '性能监控': env.ENABLE_PERFORMANCE_MONITORING ? '启用' : '禁用'
}))

const thirdPartyConfig = computed(() => ({
  'Google Maps API 密钥': env.GOOGLE_MAPS_API_KEY || '未配置',
  'Sentry DSN': env.SENTRY_DSN || '未配置',
  '百度统计 ID': env.BAIDU_ANALYTICS_ID || '未配置',
  '友盟统计 ID': env.UMENG_ANALYTICS_ID || '未配置'
}))

const businessConfig = computed(() => ({
  '默认语言': env.DEFAULT_LOCALE,
  '支持语言': env.SUPPORTED_LOCALES.join(', '),
  '默认时区': env.DEFAULT_TIMEZONE,
  '默认分页大小': env.DEFAULT_PAGE_SIZE,
  '最大分页大小': env.MAX_PAGE_SIZE,
  '最大文件大小': `${(env.MAX_FILE_SIZE / 1024 / 1024).toFixed(2)}MB`,
  '允许文件类型': env.ALLOWED_FILE_TYPES.join(', ')
}))

const devConfig = computed(() => ({
  '热重载': env.HMR_ENABLED ? '启用' : '禁用',
  '源码映射': env.SOURCE_MAP_ENABLED ? '启用' : '禁用',
  'ESLint': env.ESLINT_ENABLED ? '启用' : '禁用',
  'TypeScript 检查': env.TYPE_CHECK_ENABLED ? '启用' : '禁用',
  '模拟数据': env.MOCK_ENABLED ? '启用' : '禁用',
  '模拟延迟': env.MOCK_DELAY > 0 ? `${env.MOCK_DELAY}ms` : '无延迟'
}))

const cacheConfig = computed(() => ({
  '缓存启用': env.CACHE_ENABLED ? '启用' : '禁用',
  '缓存持续时间': `${env.CACHE_DURATION}秒`
}))

const logConfig = computed(() => ({
  '日志级别': env.LOG_LEVEL,
  '控制台日志': env.CONSOLE_LOG_ENABLED ? '启用' : '禁用'
}))

const testConfig = computed(() => ({
  '测试模式': env.TEST_MODE ? '启用' : '禁用',
  '测试用户 ID': env.TEST_USER_ID || '未配置'
}))

// 方法
const updateTime = () => {
  currentTime.value = new Date().toLocaleString('zh-CN')
}

const refreshData = () => {
  updateTime()
  console.log('环境变量数据已刷新')
}

const exportConfig = () => {
  const configData = {
    timestamp: new Date().toISOString(),
    environment: getEnvironmentInfo(),
    config: {
      app: appConfig.value,
      api: apiConfig.value,
      features: featureConfig.value,
      thirdParty: thirdPartyConfig.value,
      business: businessConfig.value,
      dev: devConfig.value,
      cache: cacheConfig.value,
      log: logConfig.value,
      test: testConfig.value
    },
    validation: validation.value
  }
  
  const blob = new Blob([JSON.stringify(configData, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `env-config-${env.APP_ENV}-${new Date().toISOString().split('T')[0]}.json`
  a.click()
  URL.revokeObjectURL(url)
}

const copyToClipboard = async () => {
  const configText = JSON.stringify({
    environment: getEnvironmentInfo(),
    config: {
      app: appConfig.value,
      api: apiConfig.value,
      features: featureConfig.value,
      thirdParty: thirdPartyConfig.value,
      business: businessConfig.value,
      dev: devConfig.value,
      cache: cacheConfig.value,
      log: logConfig.value,
      test: testConfig.value
    }
  }, null, 2)
  
  try {
    await navigator.clipboard.writeText(configText)
    alert('配置已复制到剪贴板')
  } catch (err) {
    console.error('复制失败:', err)
    alert('复制失败，请手动复制')
  }
}

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  
  if (autoRefresh.value) {
    refreshInterval.value = window.setInterval(refreshData, 5000) // 每5秒刷新
  } else {
    if (refreshInterval.value) {
      clearInterval(refreshInterval.value)
      refreshInterval.value = null
    }
  }
}

// 生命周期
onMounted(() => {
  updateTime()
  console.log('环境变量显示模块已加载')
})

onUnmounted(() => {
  if (refreshInterval.value) {
    clearInterval(refreshInterval.value)
  }
})
</script>

<style lang="scss" scoped>
.environment-app {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.app-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 2rem;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  
  h1 {
    margin: 0 0 1rem 0;
    font-size: 2.5rem;
    font-weight: 700;
  }
  
  .header-info {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 1rem;
    flex-wrap: wrap;
  }
  
  .version {
    background: rgba(255, 255, 255, 0.2);
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.9rem;
  }
  
  .env-badge {
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.9rem;
    
    &.env-dev {
      background: #e74c3c;
    }
    
    &.env-staging {
      background: #f39c12;
    }
    
    &.env-prod {
      background: #27ae60;
    }
    
    &.env-unknown {
      background: #95a5a6;
    }
  }
  
  .timestamp {
    font-size: 0.8rem;
    opacity: 0.8;
  }
}

.app-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

.env-overview {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  
  h2 {
    margin: 0 0 1.5rem 0;
    font-size: 1.8rem;
    color: #ffd700;
  }
  
  .overview-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 1rem;
  }
  
  .overview-item {
    background: rgba(255, 255, 255, 0.1);
    padding: 1rem;
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    
    strong {
      color: #ffd700;
      margin-right: 0.5rem;
    }
  }
}

.config-sections {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 2rem;
  margin-bottom: 2rem;
}

.validation-section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  
  h2 {
    margin: 0 0 1.5rem 0;
    font-size: 1.8rem;
    color: #ffd700;
  }
  
  .validation-result {
    padding: 1.5rem;
    border-radius: 8px;
    border: 2px solid;
    
    &.valid {
      background: rgba(39, 174, 96, 0.2);
      border-color: #27ae60;
    }
    
    &.invalid {
      background: rgba(231, 76, 60, 0.2);
      border-color: #e74c3c;
    }
  }
  
  .validation-status {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 1rem;
    
    .status-icon {
      font-size: 1.5rem;
    }
    
    .status-text {
      font-size: 1.2rem;
      font-weight: 600;
    }
  }
  
  .validation-errors {
    h4 {
      margin: 0 0 0.5rem 0;
      color: #ff6b6b;
    }
    
    ul {
      margin: 0;
      padding-left: 1.5rem;
      
      li {
        margin-bottom: 0.5rem;
        color: #ff6b6b;
      }
    }
  }
}

.action-panel {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 2rem;
  
  h2 {
    margin: 0 0 1.5rem 0;
    font-size: 1.8rem;
    color: #ffd700;
  }
  
  .action-buttons {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
  }
  
  .action-btn {
    padding: 0.8rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &.primary {
      background: #4CAF50;
      color: white;
      
      &:hover {
        background: #45a049;
        transform: translateY(-2px);
      }
    }
    
    &.secondary {
      background: rgba(255, 255, 255, 0.2);
      color: white;
      border: 1px solid rgba(255, 255, 255, 0.3);
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: translateY(-2px);
      }
    }
    
    &.active {
      background: #ffd700;
      color: #333;
      
      &:hover {
        background: #ffed4e;
      }
    }
  }
}

.app-footer {
  background: rgba(0, 0, 0, 0.3);
  text-align: center;
  padding: 2rem;
  margin-top: auto;
  
  p {
    margin: 0.5rem 0;
  }
  
  .footer-info {
    font-size: 0.9rem;
    opacity: 0.7;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .app-header h1 {
    font-size: 2rem;
  }
  
  .header-info {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .config-sections {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style> 